package com.diipo.weibo;

import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

import com.diipo.weibo.utils.HttpUtils;
import com.diipo.weibo.utils.SHA256; 

public class LoginActivity extends Activity implements InitViews{
	
	private String TAG = LoginActivity.class.getSimpleName();
	private Button mBtnLogin;
//	private Button mBtnClose;
	private String mUser = null;
	private String mPassword = null;
	private ImageView mGo;
	private EditText mEditTextUrl;
	private EditText mEditTextUser;
	private EditText mEditTextPasswd;
	private SharedPreferences mPrefs;
	private ProgressDialog progressDialog;
	
	private String urls="";
	private Intent mIntent;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ConfigInfo.IS_LOGOUT = true;
        // Hide title 
        requestWindowFeature( Window.FEATURE_NO_TITLE );        
        setContentView(R.layout.login);
        mPrefs = getSharedPreferences(ConfigInfo.USER_PREFERENCES,MODE_PRIVATE);
        setViews();
        setListeners();
		mUser = mPrefs.getString(ConfigInfo.PREF_USERNAME,"");
		mPassword = mPrefs.getString(ConfigInfo.PREF_PASSWORD,"");
		mIntent = getIntent();
//		String tmp = mIntent.getStringExtra(ConfigInfo.COMM.LOGOUT);
//		if(tmp.equals("yes")){
//			
//		}else{
			if(!mUser.equals("") && !mPassword.equals("") && ConfigInfo.IS_LOGOUT){
				mEditTextUser.setText(mUser);
				mEditTextPasswd.setText(mPassword);
				new LoginAsync().execute();
			}
//		}
    }
    
    private OnClickListener clickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.user_login:
				Log.e(TAG," user_login was click....");
				userLogin();
//				toMainTabs("");
				break;
			case R.id.go:  
				new GetUrlAsync().execute();
				break;
//			case R.id.close:
//				if(ConfigInfo.IS_LOGOUT){
//					Intent intent = new Intent(LoginActivity.this,SettingActivity.class);
//					startActivity(intent);
//					finish();
//				}else{
//					finish();
//				}
//				break;
			default:
				break;
			}
		}
	};
	
	private void saveAccount(String name,String passwd){
		SharedPreferences.Editor editor = mPrefs.edit();
		editor.putString(ConfigInfo.PREF_USERNAME, name);
		editor.putString(ConfigInfo.PREF_PASSWORD, passwd);
		editor.commit();
	}
	
	/**
	 * 用户登陆参数验证
	 */
	private void userLogin() {
		urls= mEditTextUrl.getText().toString().trim();
		mUser = mEditTextUser.getText().toString().trim();
		mPassword = mEditTextPasswd.getText().toString().trim();
		if (!("".equals(mUser) || "".equals(mPassword))
				&& (mUser != null || mPassword != null)&&!urls.equals("")) {
			mPassword = SHA256.Encrypt(mPassword, "");
			new LoginAsync().execute();
		} else {
			Toast.makeText(this, "用户名或密码或网址不能为空！", Toast.LENGTH_LONG).show();
		}
	}
    
    @Override
    public void getViews() {
    	// TODO Auto-generated method stub
    }
    
    @Override
    public void setViews() {
    	// TODO Auto-generated method stub
    	mBtnLogin = (Button) findViewById(R.id.user_login);
//    	mBtnClose = (Button) findViewById(R.id.close);
    	mEditTextUser = (EditText) findViewById(R.id.edittextuser);
    	mEditTextPasswd = (EditText) findViewById(R.id.edittextpassd);
    	mEditTextUrl = (EditText) findViewById(R.id.url);
    	mEditTextUrl.setText(mPrefs.getString(ConfigInfo.PREF_SERVER_ADDRESS, mPrefs.getString(ConfigInfo.PREF_SERVER_ADDRESS, ConfigInfo.COMM.CONST_SERVER_ADDRESS)));
    	mGo = (ImageView) findViewById(R.id.go);
    	mGo.setOnClickListener(clickListener);
    }
    
    @Override
    public void setListeners() {
    	// TODO Auto-generated method stub
    	mBtnLogin.setOnClickListener(clickListener);
//    	mBtnClose.setOnClickListener(clickListener);
    }
    
    public boolean onKeyDown(int keyCode, KeyEvent event) {// 捕捉返回键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Log.e(TAG," back key was click...... ");
			android.os.Process.killProcess(android.os.Process.myPid());
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
    
    @Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.e(TAG, " LoginActivity onDestroy() called ...");
	}
    /**
	 * 进入MainTabs，开始显示首页（Home）
	 * @param name
	 */
    boolean  mRet=false;
	private void toMainTabs(String name) {
//		if(name==null||"".equals(name))
//			return;
		Intent i = new Intent(LoginActivity.this, MainTabs.class);
		Bundle bundle = new Bundle();
		i.putExtras(bundle);
		startActivity(i);
	}
	
	private class LoginAsync extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... params) {
			
			StringBuffer urlss = new StringBuffer();
//			url.append(mPrefs.getString(ConfigInfo.PREF_SERVER_ADDRESS, mPrefs
//					.getString(ConfigInfo.PREF_SERVER_ADDRESS,
//							ConfigInfo.COMM.CONST_SERVER_ADDRESS)));
			 
			urlss.append(urls);
			urlss.append("/api/account/check_api.json?api_key=");
			urlss.append(ConfigInfo.COMM.APY_KEY);
			
			mRet = HttpUtils.check_url(urlss.toString());
			
			if(mRet){
				String urlAddress = mPrefs.getString(ConfigInfo.PREF_SERVER_ADDRESS, mPrefs.getString(ConfigInfo.PREF_SERVER_ADDRESS, mPrefs.getString(ConfigInfo.PREF_SERVER_ADDRESS, ConfigInfo.COMM.CONST_SERVER_ADDRESS)));
//				if (urlAddress.equals("") || urlAddress == null) {
//					urlAddress = "http://q8.diipo.cn";
//				}
				StringBuffer url = new StringBuffer();
				url.append(urlAddress);
				url.append("/api/account/verify_credentials.json?api_key=");
				url.append(ConfigInfo.COMM.APY_KEY);
				
				//String username = mPrefs.getString(ConfigInfo.PREF_USERNAME,"");
				//String passwd = mPrefs.getString(ConfigInfo.PREF_PASSWORD,"");
				String result = "";
				try {
					Log.e(TAG," user_login url = " + url.toString());
					Log.e(TAG," username = " + mUser + " , passwd = " + mPassword);
					result = HttpUtils.doGet(url.toString(), mUser, mPassword);
					Log.e(TAG," HTTP login result = " + result);
					Log.e(TAG," HTTP login result substring = " + result.substring(0, 2));
				} catch (ClientProtocolException e) {
				} catch (IOException e) {
				}
				return result;
			}else{
				 return "check_fail";
			}
			
			
		}

		@Override
		protected void onPreExecute() {
			progressDialog = new ProgressDialog(LoginActivity.this);
			progressDialog.setMessage("正在登陆中...");
			progressDialog.show();
		}
		
		@Override
		protected void onPostExecute(String result) {
			progressDialog.dismiss();
			if (result.equals("check_fail")){
				Toast.makeText(LoginActivity.this, "域名错误,请修改网址!", Toast.LENGTH_LONG).show();
			}
			else if (result != null 
					&& !result.equals("") 
					&& result != ConfigInfo.HTTPRETURN.HTTPERROR 
					&& result != ConfigInfo.HTTPRETURN.HTTP_ERROR_401
					&& !result.substring(0, 2).equals(ConfigInfo.HTTPRETURN.HTTP_ERROR_DOMAIN) ) {
				try {
					SharedPreferences.Editor editor = mPrefs.edit();
					editor.putString(ConfigInfo.PREF_SERVER_ADDRESS, urls);
					editor.commit();
//					User user = JsonUtils.parseUserFromJson(result,User.class);
					ConfigInfo.IS_LOGOUT = false;
					saveAccount(mUser,mPassword);
					Intent intent = new Intent(LoginActivity.this, MainTabs.class);
					startActivity(intent);
					finish();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				Log.e(TAG," HTTP login onPostExecute() result = " + result);
				if( result != null 
					&& !result.equals("")
					&& result.substring(0, 2).equals(ConfigInfo.HTTPRETURN.HTTP_ERROR_DOMAIN) ){
					Toast.makeText(LoginActivity.this, "域名错误,请修改网址!", Toast.LENGTH_LONG).show();
				}else{
					Toast.makeText(LoginActivity.this, "登录失败!", Toast.LENGTH_LONG).show();
				}
			}
		}
	}
	 private Spinner sp_add;
	 String[] adds;
	public void initSpinner(){
		sp_add=(Spinner) this.findViewById(R.id.add);
	   	 
	  
	   	ArrayAdapter<String> adapter1=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, adds);    
	   	adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);  
	   	sp_add.setAdapter(adapter1);    
	   	sp_add.setPrompt( " 请选择网址 ： " ); 
	   	 
	   	sp_add.setOnItemSelectedListener(new OnItemSelectedListener() {
		            public void onItemSelected(AdapterView<?> parent,
		                View view,int position,long id) { 
		            	    mEditTextUrl.setText(adds[position]);
		                }
		            public void onNothingSelected(AdapterView<?> parent) {
		            }
		                
		        }); 
	   }
	
	private class GetUrlAsync extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... params) {
			 
			StringBuffer url = new StringBuffer(); 
			url.append("http://test1.diipo.cn/api/account/api_servers.json?api_key=");
			url.append(ConfigInfo.COMM.APY_KEY); 
			String result = "";
			try {
				 
				adds = HttpUtils.get_url(url.toString()); 
				if(adds!=null&&adds.length>0)
					result="ok";
			} catch (Exception e) {
			     
			}
			return result;
		}

		@Override
		protected void onPreExecute() {
			progressDialog = new ProgressDialog(LoginActivity.this);
			progressDialog.setMessage("正在获取网址中...");
			progressDialog.show();
		}
		
		@Override
		protected void onPostExecute(String result) {
			progressDialog.dismiss();
			if (result.equals("ok")){
				initSpinner();
				sp_add.performClick();
			}else { 
				Toast.makeText(LoginActivity.this, "域名错误,请修改网址!", Toast.LENGTH_LONG).show();
				 
			}
		}
	}

}